<template>
  <div>
    <el-upload
      ref="upload"
      class="avatar-uploader"
      action=""
      list-type="picture-card"
      :on-change="handleChange"
      :before-upload="handleBeforeUpload"
      :file-list="fileList"
      :auto-upload="false"
      :show-file-list="false"
    >
      <i v-if="!this.imageUrl" class="el-icon-plus avatar-uploader-icon"></i>
      <img v-else-if="!isVideo && this.imageUrl" :src="imageUrl" class="avatar" />
      <video v-else-if="isVideo && this.imageUrl" :src="imageUrl" class="avatar"></video>
    </el-upload>
    <el-button v-if="imageUrl" @click="handlePreview">预览</el-button>
    <!-- 预览弹窗 -->
    <el-dialog :visible.sync="previewVisible" :modal="false">
      <template>
        <div v-if="!isVideo">
          <img width="100%" :src="imageUrl" alt="Preview" />
        </div>
        <div v-else>
          <video width="100%" controls>
            <source :src="imageUrl" type="video/mp4" />
            Your browser does not support the video tag.
          </video>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: {
    imageUrl: {
      type: String,
      default: null,
    },
  },
  data() {
    return {
      previewVisible: false,
      previewFile: null,
      fileList: [],
    };
  },
  computed: {
    isVideo() {
      return this.imageUrl?.endsWith('mp4') || this.previewFile?.type.endsWith('mp4');
    },
  },
  methods: {
    handlePreview() {
      this.previewVisible = true;
    },
    handleChange(file, fileList) {
      this.fileList = fileList.slice(-1); // 只保留最新上传的一张图片或视频
      this.previewFile = this.fileList[0].raw;
      this.$emit('upload', file);
    },
    handleBeforeUpload(file) {
      const type = ['image/jpg', 'image/jpeg', 'image/png', 'video/mp4'];
      if (!type.includes(file.type)) {
        return this.$message.error('只支持jpg、png、mp4格式的文件！');
      }
      if (file.size > 10 * 1024 * 1024) {
        return this.$message.error('文件大小不能超过10MB！');
      }
      return true;
    },
  },
};
</script>

<style scoped lang="less">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 100%;
  text-align: center;
}
.avatar {
  width: 100%;
  height: 100%;
  display: block;
}
// ::v-deep {
//   .el-icon-plus {
//     width: 100%;
//     height: 100%;
//   }
//   .avatar-uploader-icon {
//     line-height: 150px;
//   }
// }
</style>
